/**
 * 包含easyui的扩展和常用的方法
 */

var sy = $.extend({}, sy);/* 定义全局对象，类似于命名空间或包的作用 */
sy.config = {
    verify: {
        required: [
          /[\S]+/
          , '必填项不能为空'
        ]
      , phone: [
        /^1\d{10}$/
        , '请输入正确的手机号'
      ]
      , email: [
        /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/
        , '邮箱格式不正确'
      ]
      , url: [
        /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/
        , '链接格式不正确'
      ]
      , number: [
        /^\d+$/
        , '只能填写数字'
      ]
      , date: [
        /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/
        , '日期格式不正确'
      ]
      , identity: [
        /(^\d{15}$)|(^\d{17}(x|X|\d)$)/
        , '请输入正确的身份证号'
      ]
    }
};
/**
 * vue 和 layui form提交验证有冲突，用此方法
 */
sy.validateLayuiForm = function(form){
    formElem = $(form);
    var verify = sy.config.verify, stop = null
    , DANGER = 'layui-form-danger', field = {}
    , verifyElem = formElem.find('*[lay-verify]') //获取需要校验的元素
    , fieldElem = formElem.find('input,select,textarea') //获取所有表单域
    console.log(verifyElem);
    //开始校验
    layui.each(verifyElem, function (_, item) {
        var othis = $(this), tips = '';
        var arr = othis.attr('lay-verify').split(',');
        for (var i in arr) {
            var ver = arr[i];
            var value = othis.val(), isFn = typeof verify[ver] === 'function';
            othis.removeClass(DANGER);
            if (verify[ver] && (isFn ? tips = verify[ver](value, item) : !verify[ver][0].test(value))) {
                layer.msg(tips || verify[ver][1], {
                    icon: 5
                  , shift: 6
                });
                //非移动设备自动定位焦点
                if (!layui.device().android && !layui.device().ios) {
                    item.focus();
                }
                othis.addClass(DANGER);
                return stop = true;
            }
        }
    });

    if (stop) return false;
    return true;
}
/**
 * 判断浏览器是否是IE并且版本小于8
 */
sy.isLessThanIe8 = function() {
	return ($.browser.msie && $.browser.version < 8);
};

/**
 * @author 
 * 
 * @requires jQuery
 * 
 * 将form表单元素的值序列化成对象
 * 
 * @returns object
 */
sy.serializeObject = function(form) {
	var o = {};
	$.each(form.serializeArray(), function(index) {
		if (o[this['name']]) {
			o[this['name']] = o[this['name']] + "," + this['value'];
		} else {
			o[this['name']] = this['value'];
		}
	});
	return o;
};
//格式化位数
sy.formatNumber = function (num){
	 
	 if(0==num) return 0;
	 
	 if(!num) return ;
	 
	 if(num==null || num=='' || isNaN(num)) return;
	 
	 num = (parseFloat(num)).toFixed(2);
	 
	 if(0==num) return 0;
	 
	 num = num.replace(/^(\d*)$/,"$1.");
	 
	 num=(num+"00").replace(/(\d*\.\d\d)\d*/,"$1");
	 
	 num=num.replace(".",",");
	 
     var re=/(\d)(\d{3},)/;
     
     while(re.test(num))
    	 
    	 num = num.replace(re,"$1,$2");
     
     num = num.replace(/,(\d\d)$/,".$1");
    
	 
	 return num.replace(/^\./,"0.");  
}
/**
 * 
 * 将JSON对象转换成字符串
 * 
 * @param o
 * @returns string
 */
sy.jsonToString = function(o) {
	var r = [];
	if (typeof o == "string")
		return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
	if (typeof o == "object") {
		if (!o.sort) {
			for ( var i in o)
				r.push(i + ":" + obj2str(o[i]));
			if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
				r.push("toString:" + o.toString.toString());
			}
			r = "{" + r.join() + "}";
		} else {
			for ( var i = 0; i < o.length; i++)
				r.push(obj2str(o[i]));
			r = "[" + r.join() + "]";
		}
		return r;
	}
	return o.toString();
};
//补位
sy.pad = function(num, n,code){
	
    var len = num.toString().length;
    
    while(len < n) {
    	
        num =num +code ;
        
        len++;
    }
    
    return num;
}
sy.upperMoney =  function(num) {
    if(isNaN(num))return "无效数值！";
    var strPrefix="";
    if(num<0)strPrefix ="(负)";
    num=Math.abs(num);
    if(num>=1000000000000)return "无效数值！";
    var strOutput = "";
    var strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分';
    var strCapDgt='零壹贰叁肆伍陆柒捌玖';
    num += "00";
    var intPos = num.indexOf('.');
    if (intPos >= 0){
        num = num.substring(0, intPos) + num.substr(intPos + 1, 2);
    }
    strUnit = strUnit.substr(strUnit.length - num.length);
    for (var i=0; i < num.length; i++){
        strOutput += strCapDgt.substr(num.substr(i,1),1) + strUnit.substr(i,1);
    }
    return strPrefix+strOutput.replace(/零角零分$/, '整').replace(/零[仟佰拾]/g, '零').replace(/零{2,}/g, '零').replace(/零([亿|万])/g, '$1').replace(/零+元/, '元').replace(/亿零{0,3}万/, '亿').replace(/^元/, "零元");
}; 
sy.formLoadData = function(form,data){
	var formdata = data;
	$.each(formdata, function (key, value) {  
		//表单处理  
        var formField = form.find("[name='" + key + "']");  
        if(formField && formField.length>0){
	        var fieldTagName = formField[0].tagName.toLowerCase();  
	        if (fieldTagName == "input") {  
	            if (formField.attr("type") == "radio") {  
	                $("input:radio[name='" + key + "'][value='" + value + "']").attr("checked", "checked");  
	            } else if (formField.attr("type") == "checkbox") { 
	                $("input:checkbox[name='" + key + "'][value='" + value + "']").attr("checked", "checked");  
	            } else { 
	                formField.val(value);  
	            }  
	        }  else if (fieldTagName == "label") {  
	            formField.html(value);  
	        } else {  
	            formField.val(value);  
	        }  
        }
	});
}
sy.formLoadDataVue = function(form,data,vueForm){
	var formdata = data;
	$.each(formdata, function (key, value) {  
		//表单处理  
        var formField = form.find("[name='" + key + "']");  
        if(formField && formField.length>0){
        	vueForm[key] = value;
	        var fieldTagName = formField[0].tagName.toLowerCase();  
	        if (fieldTagName == "input") {  
	            if (formField.attr("type") == "radio") {  
	                $("input:radio[name='" + key + "'][value='" + value + "']").attr("checked", "checked");  
	            } else if (formField.attr("type") == "checkbox") { 
	                $("input:checkbox[name='" + key + "'][value='" + value + "']").attr("checked", "checked");  
	            } else { 
	                formField.val(value);  
	            }  
	        }  else if (fieldTagName == "label") {  
	            formField.html(value);  
	        } else {  
	            formField.val(value);  
	        }  
        }
	});
}
sy.urlParam = function(name) {
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r!=null)return  unescape(r[2]); return null;
};
sy.loadSelectData=function(parentCode,res){
	$.ajax({
		url :staticURL+'/basic/baseInfoAction/combox?parentCode='+parentCode,
		dataType : 'json',
		success : function(json) {
			res = json;
		}
	});
}
/**
 * 格式化日期时间
 * 
 * @param format
 * @returns
 */
Date.prototype.format = function(format) {
	if (isNaN(this.getMonth())) {
		return '';
	}
	if (!format) {
		format = "yyyy-MM-dd hh:mm:ss";
	}
	var o = {
		/* month */
		"M+" : this.getMonth() + 1,
		/* day */
		"d+" : this.getDate(),
		/* hour */
		"h+" : this.getHours(),
		/* minute */
		"m+" : this.getMinutes(),
		/* second */
		"s+" : this.getSeconds(),
		/* quarter */
		"q+" : Math.floor((this.getMonth() + 3) / 3),
		/* millisecond */
		"S" : this.getMilliseconds()
	};
	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
};

/**
 * @author 
 * 
 * @requires jQuery
 * 
 * 改变jQuery的AJAX默认属性和方法
 */
$.ajaxSetup({
	type : 'POST',
	error : function(XMLHttpRequest, textStatus, errorThrown) {
		if(XMLHttpRequest.getResponseHeader("sessionstatus")=='timeout'){
			var text = XMLHttpRequest.responseText;
			var data = $.parseJSON(text);
			window.location.href=data.path;
		}else{
			alert("数据加载异常！请联系管理员" );
		}
	}
});

const Bus = new Vue();